package com.example.k12.utlis

import android.content.Context
import android.graphics.Bitmap
import android.os.RemoteException
import android.text.TextUtils
import android.util.Log
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import com.blankj.utilcode.util.LogUtils
import com.example.k12.app.MyApp.Companion.getContext
import com.example.k12.utlis.AppConfig.Companion.instance
import com.tencent.wxpayface.IWxPayfaceCallback
import com.tencent.wxpayface.WxPayFace
import com.tencent.wxpayface.constants.FacePayConstants
import com.tencent.wxpayface.data.UserInfo
import java.util.concurrent.TimeUnit

object WxPayUtils {
    private const val TAG = "WxPayUtils"

    private const val FACE_UPDATE_WORK_NAME = "face_data_update_work"

    /**
     * 启动人脸数据定时更新任务（每小时执行一次）
     */
    fun schedulePeriodicFaceUpdate(context: Context) {
        // 创建周期性工作请求，每小时执行一次
        val faceUpdateWork =
            PeriodicWorkRequest.Builder(FaceDataUpdateWorker::class.java, 1, TimeUnit.HOURS)
                .build()

        // 加入工作队列，如果已存在同名任务则替换
        WorkManager.getInstance(context)
            .enqueueUniquePeriodicWork(
                FACE_UPDATE_WORK_NAME,
                ExistingPeriodicWorkPolicy.REPLACE,
                faceUpdateWork
            )

        LogUtils.d(TAG, "已安排人脸数据定时更新任务，每小时执行一次")
    }

    /**
     * 取消人脸数据定时更新任务
     */
    fun cancelPeriodicFaceUpdate(context: Context) {
        WorkManager.getInstance(context).cancelUniqueWork(FACE_UPDATE_WORK_NAME)
        LogUtils.d(TAG, "已取消人脸数据定时更新任务")
    }

    @JvmStatic
    val params: HashMap<String, String>
        get() {
            val params =
                java.util.HashMap<String, String>()
            if (!TextUtils.isEmpty(instance.authInfo)) {
                params.put("authinfo", instance.authInfo!!)
            }
            params.put("appid", instance.deviceInfo!!.payAppId)
            params.put("mch_id", instance.deviceInfo!!.payMchId)
            params.put("mch_name", instance.deviceInfo!!.schoolName)
            params.put("sub_mch_id", instance.deviceInfo!!.subMchId)
            params.put("organization_id", instance.deviceInfo!!.organizationId)
            return params
        }

    fun initPayFace(context: Context?) {
        WxPayFace.getInstance()
            .initWxpayface(context, java.util.HashMap<Any?, Any?>(), object : IWxPayfaceCallback() {
                @Throws(RemoteException::class)
                override fun response(info: MutableMap<*, *>?) {
                    if (info == null) {
                        RuntimeException("微信初始化调用返回为空").printStackTrace()
                        return
                    }
                    val code = info.get("return_code") as String?
                    val msg = info.get("return_msg") as String?
                    LogUtils.d(TAG, "response info :: " + code + " | " + msg)
                    if (code == null || code != "SUCCESS") {
                        RuntimeException("微信初始化失败: " + msg).printStackTrace()
                        return
                    }
                    LogUtils.d(TAG, "调用返回成功")
                    wxPayFaceRawdata
                }
            })
    }

    private val wxPayFaceRawdata: Unit
        get() {
            WxPayFace.getInstance().getWxpayfaceRawdata(object : IWxPayfaceCallback() {
                @Throws(RemoteException::class)
                override fun response(info: MutableMap<*, *>?) {
                    if (info == null) {
                        RuntimeException("rawdata调用返回为空").printStackTrace()
                        return
                    }
                    val code = info.get("return_code") as String?
                    val msg = info.get("return_msg") as String?
                    val rawdata = info.get("rawdata") as String?
                    LogUtils.d(
                        TAG,
                        "getWxpayfaceRawdata response info :: " + code + " | " + msg + " | " + rawdata
                    )
                    if (code == null || rawdata == null || (code != "SUCCESS")) {
                        RuntimeException("rawdata调用失败,return_msg:" + msg)
                            .printStackTrace()
                        return
                    }
                    instance.rawdata = rawdata
                    //                //更新人脸库 数据
//                manualUpdateFaceDatas();
                }
            })
        }

    /**
     * 手动更新人脸库数据
     */
    fun manualUpdateFaceDatas(errCallback: ((String?) -> Unit?)? = null) {
        LogUtils.d(TAG, "更新人脸信息")
        //params包含请求通用参数(authinfo,mch_id等)
        WxPayFace.getInstance().manualUpdateFaceDatas(params, object : IWxPayfaceCallback() {
            @Throws(RemoteException::class)
            override fun response(info: MutableMap<*, *>?) {
                schedulePeriodicFaceUpdate(getContext())
                DialogUtil.getInstance().dismissDialog()
                if (info == null) {
                    RuntimeException("更新人脸信息返回为空：").printStackTrace()
                    errCallback?.invoke("更新人脸信息返回为空")
                    return
                }
                val code = info["return_code"] as String?
                val msg = info["return_msg"] as String?
                if (code == null || code != "SUCCESS") {
                    RuntimeException("更新人脸信息调用失败,return_msg:$msg").printStackTrace()
                    errCallback?.invoke("更新人脸信息调用失败,return_msg:$msg")
                    return
                }
            }
        })
    }

    fun preloadEnv() {
        //params包含请求通用参数(authinfo,mch_id等)
        WxPayFace.getInstance().preloadSdkEnv(params, object : IWxPayfaceCallback() {
            @Throws(RemoteException::class)
            override fun response(info: MutableMap<*, *>?) {
                if (info == null) {
                    RuntimeException("调用返回为空").printStackTrace()
                    return
                }
                val code = info.get("return_code") as String?
                val msg = info.get("return_msg") as String?
                if (code == null || code != "SUCCESS") {
                    RuntimeException("调用返回非成功信息,return_msg:" + msg).printStackTrace()
                    return
                }
            }
        })
    }


    fun startVerify() {
        //params包含请求通用参数(authinfo,mch_id等)
        WxPayFace.getInstance().startVerify(params, object : IWxPayfaceCallback() {
            @Throws(RemoteException::class)
            override fun response(info: MutableMap<*, *>?) {
                if (info == null) {
                    RuntimeException("调用返回为空").printStackTrace()
                    return
                }
                val code = info.get("return_code") as String?
                val msg = info.get("return_msg") as String?
                if (code == null || code != "SUCCESS") {
                    RuntimeException("调用返回非成功信息,return_msg:" + msg).printStackTrace()
                    return
                }
                val userInfos = info.get("user_info_list") as MutableList<UserInfo?>?
                //是否需要辅助验证
                val needExtVerify =
                    (info.get(FacePayConstants.KEY_RET_PARAMS_NEED_EXT_VERIFY)) as Boolean?
                val bitmap = info.get("best_face_img") as Bitmap?
            }
        })
    }
}

